<template>
  <div class="department-management-container">


    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-form-wrapper">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="部门名称">
            <el-input 
              v-model="searchForm.departmentName" 
              placeholder="请输入部门名称" 
              clearable 
              style="width: 220px;"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择" 
              clearable 
              style="width: 160px;"
            >
              <el-option label="正常" value="正常" />
              <el-option label="停用" value="停用" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleSearch"
              class="search-button"
              :icon="Search"
            >
              搜索
            </el-button>
            <el-button 
              @click="handleReset"
              :icon="Refresh"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="add-button-wrapper">
        <el-button 
          type="primary" 
          @click="handleAddDepartment"
          class="add-department-btn"
          :icon="Plus"
        >
          添加部门
        </el-button>
      </div>
    </div>

    <!-- 部门列表统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card total-departments">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon><OfficeBuilding /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ totalCount }}</div>
            <div class="stat-label">总部门数</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card active-departments">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ activeCount }}</div>
            <div class="stat-label">正常部门</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card inactive-departments">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon><Close /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ inactiveCount }}</div>
            <div class="stat-label">停用部门</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 部门列表表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="currentPageData"
        style="width: 100%;"
        border
        fit
        :row-class-name="tableRowClassName"
        @row-hover="handleRowHover"
        @row-click="handleRowClick"
        empty-text="暂无数据"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="部门名称" min-width="180">
          <template #default="scope">
            <div class="department-name">
              <el-icon class="name-icon"><OfficeBuilding /></el-icon>
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              class="status-tag"
              effect="light"
            >
              {{ scope.row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后修改时间" min-width="200">
          <template #default="scope">
            <div class="update-time">
              <el-tooltip :content="formatDateTime(scope.row.updateTime)" placement="top">
                <span>{{ formatDateTime(scope.row.updateTime) }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleEdit(scope.row)"
                :icon="Edit"
                class="edit-btn"
              >
                修改
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(scope.row)"
                :icon="Delete"
                class="delete-btn"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <div class="pagination-info">
        <el-icon><Document /></el-icon>
        <span>共 {{ totalCount }} 条记录</span>
      </div>
      <div class="pagination-controls">
          <el-select 
            v-model="pageSize" 
            @change="handleSizeChange" 
            style="width: 100px; margin-right: 15px;"
            size="small"
          >
            <el-option :label="'10条/页'" :value="10" />
            <el-option :label="'20条/页'" :value="20" />
            <el-option :label="'50条/页'" :value="50" />
          </el-select>
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            layout="prev, pager, next"
            :total="totalCount"
            @current-change="handleCurrentChange"
            background
            small
            hide-on-single-page
          />
      </div>
    </div>

    <!-- 添加部门对话框 -->
    <el-dialog 
      v-model="dialogVisible.add" 
      title="新增部门" 
      width="500px"
      destroy-on-close
      :before-close="handleDialogClose"
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input 
            v-model="addForm.name" 
            placeholder="请输入部门名称" 
            maxlength="10" 
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="部门状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择部门状态">
            <el-option label="正常" value="正常" />
            <el-option label="停用" value="停用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.add = false">取消</el-button>
          <el-button type="primary" @click="handleAddConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改部门对话框 -->
    <el-dialog 
      v-model="dialogVisible.edit" 
      title="修改部门" 
      width="500px"
      destroy-on-close
      :before-close="handleDialogClose"
    >
      <el-form 
        :model="editForm" 
        :rules="rules" 
        ref="editFormRef" 
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input 
            v-model="editForm.name" 
            placeholder="请输入部门名称" 
            maxlength="10" 
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="部门状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择部门状态">
            <el-option label="正常" value="正常" />
            <el-option label="停用" value="停用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.edit = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDepartmentPage, addDepartment, updateDepartment, deleteDepartment } from '@/api/department'
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete,
  OfficeBuilding,
  Check,
  Close,
  Document
} from '@element-plus/icons-vue'

// 状态管理
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const jumpPage = ref(1)
const hoverRow = ref(null)
const selectedRow = ref(null)

// 搜索表单
const searchForm = reactive({
  departmentName: '',
  status: ''
})

// 对话框可见性
const dialogVisible = reactive({
  add: false,
  edit: false
})

// 添加表单
const addForm = reactive({
  name: '',
  status: '正常'
})

// 修改表单
const editForm = reactive({
  id: '',
  name: '',
  status: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 10, message: '部门名称长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择部门状态', trigger: 'change' }
  ]
}

// 表单引用
const addFormRef = ref()
const editFormRef = ref()

// 部门数据
const departments = ref([])
// 总记录数
const totalCount = ref(0)

// 计算当前页显示的数据
const currentPageData = computed(() => {
  return departments.value
})

// 计算正常部门数量
const activeCount = computed(() => {
  return departments.value.filter(dept => dept.status === 1).length
})

// 计算停用部门数量
const inactiveCount = computed(() => {
  return departments.value.filter(dept => dept.status === 0).length
})

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  if (isNaN(date.getTime())) return '-'
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 处理表格行悬停
const handleRowHover = (row, event) => {
  hoverRow.value = row
}

// 处理表格行点击
const handleRowClick = (row, event) => {
  selectedRow.value = row
}

// 表格行类名
const tableRowClassName = ({ rowIndex }) => {
  return `row-${rowIndex % 2}`
}

// 处理对话框关闭
const handleDialogClose = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 加载部门数据
const loadDepartments = async () => {
  loading.value = true
  try {
    const params = {
      name: searchForm.departmentName,
      status: searchForm.status === '正常' ? 1 : searchForm.status === '停用' ? 0 : undefined,
      page: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await getDepartmentPage(params)
    departments.value = response.data.rows || []
    totalCount.value = response.data.total || 0
  } catch (error) {
    console.error('获取部门列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  jumpPage.value = 1
  loadDepartments()
}

// 清空搜索
const handleReset = () => {
  searchForm.departmentName = ''
  searchForm.status = ''
  currentPage.value = 1
  jumpPage.value = 1
  loadDepartments()
}

// 显示添加部门对话框
const handleAddDepartment = () => {
  addForm.name = ''
  addForm.status = '正常'
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  dialogVisible.add = true
}

// 处理添加确认
const handleAddConfirm = async () => {
  if (addFormRef.value) {
    await addFormRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          const data = {
            name: addForm.name,
            status: addForm.status === '正常' ? 1 : 0
          }
          await addDepartment(data)
          dialogVisible.add = false
          ElMessage.success('添加成功')
          loadDepartments() // 重新加载数据
        } catch (error) {
          console.error('添加部门失败:', error)
        } finally {
          loading.value = false
        }
      }
    })
  }
}

// 处理修改
const handleEdit = (row) => {
  editForm.id = row.id
  editForm.name = row.name
  editForm.status = row.status === 1 ? '正常' : '停用'
  dialogVisible.edit = true
}

// 处理修改确认
const handleEditConfirm = async () => {
  if (editFormRef.value) {
    await editFormRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          const dept = {
            id: editForm.id,
            name: editForm.name,
            status: editForm.status === '正常' ? 1 : 0
          }
          await updateDepartment(dept)
          dialogVisible.edit = false
          ElMessage.success('修改成功')
          loadDepartments() // 重新加载数据
        } catch (error) {
          console.error('修改部门失败:', error)
        } finally {
          loading.value = false
        }
      }
    })
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '您确认删除该部门吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      loading.value = true
      try {
        await deleteDepartment(row.id)
        ElMessage.success('删除成功')
        loadDepartments() // 重新加载数据
      } catch (error) {
        console.error('删除部门失败:', error)
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}



// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  jumpPage.value = 1
  loadDepartments()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  jumpPage.value = current
  loadDepartments()
}

// 页面跳转
const handleJump = () => {
  const maxPage = Math.ceil(totalCount.value / pageSize.value)
  if (jumpPage.value >= 1 && jumpPage.value <= maxPage) {
    currentPage.value = jumpPage.value
    loadDepartments()
  } else {
    ElMessage.warning('请输入有效的页码')
    jumpPage.value = currentPage.value
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadDepartments()
})
</script>

<style scoped>
/* 基础容器样式 */
.department-management-container {
  padding: 30px;
  background-color: #f0f2f5;
  min-height: 100vh;
  transition: all 0.3s ease;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 30px;
  animation: fadeIn 0.6s ease-in-out;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
  line-height: 1.6;
}

/* 搜索区域样式 */
.search-area {
  background-color: #ffffff;
  padding: 25px;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.search-area:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.search-form-wrapper {
  flex: 1;
  min-width: 500px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.search-button {
  transition: all 0.3s ease;
}

.search-button:hover {
  transform: translateY(-1px);
}

.add-button-wrapper {
  display: flex;
  justify-content: flex-end;
}

.add-department-btn {
  transition: all 0.3s ease;
  font-weight: 500;
  padding: 8px 20px;
}

.add-department-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(48, 164, 255, 0.3);
}

/* 统计卡片样式 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px !important;
  overflow: hidden;
  transition: all 0.3s ease;
  border: none !important;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.total-departments {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.active-departments {
  background: linear-gradient(135deg, #66bb6a 0%, #43a047 100%);
  color: white;
}

.inactive-departments {
  background: linear-gradient(135deg, #ff7675 0%, #e17055 100%);
  color: white;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 16px 0;
}

.stat-icon {
  font-size: 32px;
  margin-right: 16px;
  opacity: 0.9;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  line-height: 1.2;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

/* 表格容器样式 */
.table-container {
  background-color: #ffffff;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
}

.table-container:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

/* 表格样式覆盖 */
:deep(.el-table) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-table .el-table__header-wrapper th) {
  background-color: #fafafa;
  font-weight: 600;
  font-size: 14px;
  color: #303133;
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table .el-table__body-wrapper) {
  padding-bottom: 8px;
}

:deep(.el-table .el-table__row) {
  transition: all 0.3s ease;
  cursor: pointer;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa !important;
  transform: translateY(-1px);
}

:deep(.el-table .el-table__row.row-0) {
  background-color: #ffffff;
}

:deep(.el-table .el-table__row.row-1) {
  background-color: #fafafa;
}

:deep(.el-table .el-table__fixed-right) {
  height: 100% !important;
  border-radius: 0 12px 12px 0;
}

:deep(.el-table .el-table__column--selection) {
  background-color: #fafafa !important;
}

/* 表格内容样式 */
.department-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.name-icon {
  color: #409eff;
  font-size: 16px;
}

.status-tag {
  font-size: 12px;
  padding: 2px 10px;
  border-radius: 10px;
}

.update-time {
  font-size: 13px;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.edit-btn {
  padding: 4px 12px;
  font-size: 12px;
  transition: all 0.3s ease;
}

.delete-btn {
  padding: 4px 12px;
  font-size: 12px;
  transition: all 0.3s ease;
}

/* 分页容器样式 */
.pagination-container {
  background-color: #ffffff;
  padding: 20px 25px;
  border-radius: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.pagination-container:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.pagination-info {
  color: #606266;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 对话框样式 */
.dialog-form {
  padding: 10px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 25px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 25px;
}

:deep(.el-dialog__footer) {
  padding: 15px 25px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-dialog__closeBtn) {
  color: white;
  opacity: 0.8;
}

:deep(.el-dialog__closeBtn:hover) {
  opacity: 1;
}

/* 分页样式覆盖 */
:deep(.el-pagination.is-background .el-pager li) {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  margin: 0 3px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled):not(.active):hover) {
  color: #409eff;
  background-color: #ecf5ff;
  transform: translateY(-1px);
}

:deep(.el-pagination.is-background .el-pager li.active) {
  background-color: #409eff;
  color: #ffffff;
  font-weight: 500;
  transform: translateY(-1px);
}

/* 加载动画 */
:deep(.el-loading-spinner .path) {
  stroke: #409eff;
}

:deep(.el-loading-spinner .el-loading-text) {
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .department-management-container {
    padding: 20px;
  }
  
  .search-area {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form-wrapper {
    min-width: 100%;
  }
  
  .add-button-wrapper {
    justify-content: flex-start;
  }
}

@media (max-width: 768px) {
  .department-management-container {
    padding: 15px;
  }
  

  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .pagination-container {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .pagination-controls {
    justify-content: center;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 确保表格在小屏幕上正常显示 */
:deep(.el-table) {
  min-width: 100%;
}

:deep(.el-table__body) {
  transition: all 0.3s ease;
}

/* 优化表单组件样式 */
:deep(.el-input__inner) {
  transition: all 0.3s ease;
}

:deep(.el-input__inner:focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-select__input.is-focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>